<script setup lang="ts">
import { RouterView } from 'vue-router'
import { backendService } from '@/service/BackendService'
import { isAuthenticated, useAuthorizationStore } from '@/service/AuthorizationService'
import router from '@/router'

const activePath = () => {
  let curRoute = router.currentRoute.value
  if (curRoute.matched.length > 0) {
    return curRoute.matched[0].path
  } else {
    return curRoute.path
  }
}

const logout = () => {
  ElMessageBox.confirm('确定要退出吗?', '提示', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning'
  }).then(() => {
    backendService
      .post('/api/logout', {})
      .then(() => {})
      .finally(() => {
        useAuthorizationStore().signOut()
        router.push({ path: '/login' })
      })
  })
}
</script>

<template>
  <el-container>
    <el-header>
      <el-menu :default-active="activePath()" mode="horizontal" :router="true" :ellipsis="false">
        <el-menu-item index="/">
          <img src="@/assets/logo.svg" style="height: 48px" alt="Logo" />
        </el-menu-item>
        <el-menu-item index="/history">同步记录</el-menu-item>
        <el-menu-item index="/file">文件信息</el-menu-item>
        <el-menu-item index="/statistics">统计</el-menu-item>
        <el-menu-item index="/log">日志</el-menu-item>
        <div class="flex-grow"></div>
        <el-menu-item index="/change">变更日志</el-menu-item>
        <el-sub-menu v-if="false" index="language">
          <template #title>
            <icon-language></icon-language>
          </template>
          <el-menu-item>中文</el-menu-item>
          <el-menu-item>英语</el-menu-item>
        </el-sub-menu>
        <el-menu-item>
          <el-link href="https://github.com/xiyoufang/cloud-syncer" target="_blank" :underline="false">
            <template #icon>
              <icon-github></icon-github>
            </template>
          </el-link>
        </el-menu-item>
        <el-menu-item v-if="!isAuthenticated()" index="/login">登录</el-menu-item>
        <el-menu-item v-if="isAuthenticated()" @click="logout">注销</el-menu-item>
      </el-menu>
    </el-header>
    <el-main>
      <router-view />
    </el-main>
    <el-footer>
      <div>微信公众号 "开源螺丝钉" ©2024</div>
    </el-footer>
  </el-container>
</template>

<style lang="less" scoped>
.el-header {
  padding: 0 0;

  .flex-grow {
    flex-grow: 1;
  }
}

.el-footer {
  line-height: var(--el-footer-height);
  text-align: center;
}
</style>
